<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;

class UserAddressModel extends Model
{
    protected $table = 'user_addresses';

    protected $fillable = [
        'user_id',
        'province',
        'provinceid',
        'city',
        'cityid',
        'district',
        'districtid',
        'address',
        'isdefault',
        'lng',
        'lat',
        'gd_lng',
        'gd_lat',
        'contact_name',
        'contact_phone',
        'last_used_at',
    ];
    protected $dates = ['last_used_at'];

    // 地址所属用户
    public function user()
    {
        return $this->belongsTo(UserModel::class);
    }

    public function getFullAddressAttribute()
    {
        return "{$this->province}{$this->city}{$this->district}{$this->address}";
    }

    public static function getCompanyID($provinceID)
    {
        $cityAlias = [
            '1' => '9', //北京
            '600' => '49', //杭州
            '1366' => '53', //武汉
            '1207' => '54', //天津
            '1622' => '63', //南京
            '1781' => '65', //广州
            '540' => '70', //上海
            '178' => '77', //深圳
            '2232' => '111', //成都
            '6688100' => '8866100', //长沙
            '6688200' => '8866200', //青岛
            '6688300' => '8866300', //重庆
        ];
        if ($provinceID > 0 && isset($cityAlias["$provinceID"])) {
            return $cityAlias["$provinceID"];
        } else {
            return 0;
        }
    }

    /**
     * 获取默认地址信息
     * @param int $uid
     *
     * @return \Illuminate\Database\Eloquent\Builder|Model|null|object
     */
    public function getDefaultAddress(int $uid)
    {
        return UserAddressModel::query()
            ->where('user_id', '=', $uid)
            ->where('isdefault', '=', 1)
            ->first();
    }

    /**
     * 最后设置的地址
     * @param int $uid
     * @return Model|null|object|static
     */
    public function getLastSetAddress(int $uid)
    {
        return UserAddressModel::query()
            ->where('user_id', '=', $uid)
            ->orderBy('created_at', 'desc')
            ->first();
    }
}
